package com.crm.service.impl;

import com.crm.entity.UserChecks;
import com.crm.repository.UserCheckRepository;
import com.crm.service.UserChecksService;
import com.crm.util.FenyeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 
 * @date 2020/5/11 16:46
 */
@Service
public class UserChecksServiceImpl implements UserChecksService {
    @Autowired
    private UserCheckRepository userChecksRepository;
    @Override
    public FenyeUtil<UserChecks> findAllByPage(UserChecks userChecks,Integer page) {
        FenyeUtil<UserChecks> f=new FenyeUtil<>();

        List<Sort.Order> orders = new ArrayList<>();
        orders.add(new Sort.Order(Sort.Direction.DESC, "checkInTime"));
        Sort sort = new Sort(orders);
        PageRequest of = PageRequest.of(page - 1, 10,sort);
        Page<UserChecks> all = userChecksRepository.findAll(get(userChecks), of);
        f.setData(all.getContent());
        f.setCount((int) all.getTotalElements());
        return f;
    }

    private Specification<UserChecks> get(UserChecks userChecks) {
        return  new Specification<UserChecks>() {
            @Override
            public Predicate toPredicate(Root<UserChecks> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                Predicate conjunction = criteriaBuilder.conjunction();
                List<Expression<Boolean>> expressions = conjunction.getExpressions();
                if(!StringUtils.isEmpty(userChecks.getUserName())){
                    expressions.add(criteriaBuilder.like(root.get("userName"),"%"+userChecks.getUserName()+"%"));
                }
                if(!StringUtils.isEmpty(userChecks.getCheckInTime())){
                    expressions.add(criteriaBuilder.like(root.get("checkInTime"),userChecks.getCheckInTime()+"%"));
                }
                if(!StringUtils.isEmpty(userChecks.getCheckState())){
                    expressions.add(criteriaBuilder.equal(root.get("checkState"),userChecks.getCheckState()));
                }
                return conjunction;
            }
        };
    }

    @Override
    public String addUserChecks(UserChecks userChecks) {

        try {
            userChecksRepository.save(userChecks);
            return "添加成功";
        } catch (Exception e) {
            return "添加失败";
        }
    }


}
